from datetime import datetime, timedelta

from django.shortcuts import render,redirect

from loginRegister import settings
from .utils import hash_code, make_confirm_string, send_email
from .forms import LoginForm
from .forms import RegisterForm
from login.models import SiteUser, ConfirmString


# Create your views here.
def index(request): #只有登录才能进入首页
    if request.session.get('is_login'):
        return render(request,'login/index.html')
    return redirect('/login/')
def login(request):
    if request.method=='POST':
        login_form=LoginForm(request.POST) #1、实例化表单对象
        if login_form.is_valid():#2、验证表单数据的合法性
            username = login_form.cleaned_data.get('username')#3、获取表单数据并清洗
            password = login_form.cleaned_data.get('password')
            user=SiteUser.objects.filter(name=username,password=hash_code(password)).first()
            if user:
                if not user.has_confirmed:
                    message="该用户还未经过邮件确认！"
                    return render(request,'login/login.html',locals())
                request.session['is_login']=True
                request.session['user_id']=user.id
                request.session['username']=user.name
                return redirect('/index')
            else:
                message="用户名或者密码错误"
                #return render(request, 'login/login.html',{'message':message})
                return render(request, 'login/login.html',locals())
                #locals()以字典方式返回所有的内部变量，例如{'message':'xxxxx','login_form':'xxxxx'}
        else:
            message="填写的登录信息不合法"
            return render(request,'login/login.html',locals())#locals获取所有内部变量
    login_form=LoginForm()
    return render(request, 'login/login.html',locals())
def logout(request):
    if request.session.get('is_login'): # 如果状态不是登录状态，就无法登出
        request.session.flush() #清空session信息
    return redirect('/login/')# redirect：重定向，跳转某一个路由
def register(request):
    #pass
    # 如果用户已经登录，则不能注册，跳转至首页。
    if request.session.get('is_login',None):
        return redirect('/index/')
    # post方法
    if request.method=='POST':
        print(request.POST)
        register_form=RegisterForm(request.POST)
        message="请检查填写的内容"
        print(message)
        if register_form.is_valid():#先验证提交的数据是否通过
            # 清洗数据
            username=register_form.cleaned_data.get('username')
            password1=register_form.cleaned_data.get('password1')
            password2=register_form.cleaned_data.get('password2')
            email=register_form.cleaned_data.get('email')
            print("清洗数据")
            # 判断用户名和邮箱是否已经被注册
            same_name_user=SiteUser.objects.filter(name=username)
            print("相同用户名",same_name_user)
            if same_name_user:
                message="用户名已存在"
                print(message)
                return render(request, 'login/register.html', locals())
            same_email_user = SiteUser.objects.filter(email=email)
            if same_email_user:
                message="该邮箱已经被注册"
                return render(request,'login/register.html',locals())
            try:
              #将注册信息存储到数据库，跳转到登录界面....将注册的密码加密之后再存储
              new_user=SiteUser(name=username,password=hash_code(password1),email=email)
              new_user.save()
              #生成确认码，并发送邮件
              code=make_confirm_string(new_user)
              send_email(email,code)
              message='请前往邮箱确认'
            except Exception:
               new_user.delete()
               message="发送邮件失败"
               return render(request, 'login/register.html', locals())
            else:
              return redirect('/login/')
    #返回用户注册的HTML页面
    register_form=RegisterForm()
    return render(request,'login/register.html',locals()) #将当前变量封装成字典，返回给前端

def user_confirm(request):
    code = request.GET.get('code', None)
    message = ''
    try:
        confirm = ConfirmString.objects.get(code=code)
    except:
        message = '无效的确认请求!'
        return render(request, 'login/confirm.html', locals())
    create_time = confirm.create_time
    now = datetime.now()
    print(now, create_time, create_time + timedelta(settings.CONFIRM_DAYS))
    if now > create_time + timedelta(settings.CONFIRM_DAYS):
        confirm.user.delete()
        message = '您的邮件已经过期！请重新注册!'
    else:
        confirm.user.has_confirmed = True
        confirm.user.save()
        confirm.delete()
        message = '感谢确认，请使用账户登录！'
    return render(request, 'login/confirm.html', locals())
